package com.pig.openg1.graphics;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.AttributeSet;

import com.pig.openg1.data.TextureData;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/***
 * 纹理图的尺寸为 2 的指数次幂
 *加载三角形纹理
 */
public class DrawView4 extends GLSurfaceView{

    private final String TAG = DrawView4.class.getSimpleName();

    private TextureData mData;

    public DrawView4(Context context) {
        super(context);
        init();
    }

    public DrawView4(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init()
    {
        setEGLContextClientVersion(2);
        setRenderer(new TextureRender());
        setRenderMode(RENDERMODE_CONTINUOUSLY);
    }

    private class TextureRender implements Renderer{

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {

            GLES20.glClearColor(0,0,0,1);

            //打开深度测试
            GLES20.glEnable(GLES20.GL_DEPTH_TEST);

            //关闭背面剪裁
            GLES20.glDisable(GLES20.GL_CULL_FACE);

            mData = new TextureData(DrawView4.this.getContext());
            //初始化纹理
            mData.initTexture();
        }

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {

            GLES20.glViewport(0,0,width,height);
            float ratio = (float) width / height;
            //设置相机位置
            Matrix.frustumM(mData.mProjMatrix,0,-ratio,ratio,-1,1,1,20);

            //设置视口位置
            Matrix.setLookAtM(mData.mVMatrix,0,
                    0F, 0F, 5,
                    0,0,0,
                    1f, 0.5f, 0f);
            //0f, 1.0f, 0.0f:正常的
            //0f, -1.0f, 0.0f:倒立的
            //1f, 0.0f, 0.0f:向左
            //1f, -1f, 0.0f:左下
        }

        @Override
        public void onDrawFrame(GL10 gl) {

            GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT| GLES20.GL_COLOR_BUFFER_BIT);

            //绘制
            mData.drawSelf();

        }
    }

}
